﻿#include "HomeController.h"
#include "TransactionController.h"
#include "PlayerController.h"

HomeController::HomeController(){}

HomeController::~HomeController(){}

void HomeController::viewDidLoad(){
	CAView* view=this->getView();
	//查询
	CAView* subview=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_H(0, 400)), themeColor);
	CAImageView* location=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(20, 26), DVerticalLayout_T_H(50, 35)));
	location->setImage(CAImage::create("img/location.png"));
	subview->addSubview(location);
	CALabel* addr=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(55, 100), DVerticalLayout_T_H(50, 35)));
	addr->setText("济南");
	addr->setFontSize(40);
	addr->setColor(CAColor4B::WHITE);
	subview->addSubview(addr);
	CATextField* search=CATextField::createWithLayout(DLayout(DHorizontalLayout_L_R(160, 90), DVerticalLayout_T_H(33, 70)));
	search->setMarginImageLeft(DSize(57, 59), "img/search.png");
	subview->addSubview(search);
	CAImageView* sort=CAImageView::createWithLayout(DLayout(DHorizontalLayout_R_W(20, 43), DVerticalLayout_T_H(45, 43)));
	sort->setImage(CAImage::create("img/sort.png"));
	subview->addSubview(sort);
	view->addSubview(subview);
	//轮播
	sendHttp(view, "/api/sysBananer/appBananer", "", CALLBACK_BIND_1(HomeController::bananerData, this), CAHttpRequest::Type::Post, true, true);
	//页签
	float width=(view->getBounds().size.width-80)/3;
	subview=CAView::createWithLayout(DLayout(DHorizontalLayout_L_W(20, width), DVerticalLayout_T_H(550, 100)), themeColor);
	CAImageView* img=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(5, 45), DVerticalLayout_H_C(45, 0.5)));
	img->setImage(CAImage::create("img/trade.png"));
	subview->addSubview(img);
	CALabel* label=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(55, 150), DVerticalLayout_H_C(45, 0.5)));
	label->setText("交易大厅");
	label->setFontSize(35);
	label->setColor(CAColor4B::WHITE);
	subview->addSubview(label);
	subview->onTouchBegan([&](CATouch* touch, CAEvent* event){
		CATabBarController* bar=(CATabBarController*)(getRootWindow()->getViewControllerAtIndex(0));
		bar->showSelectedViewControllerAtIndex(1);

		return true;
	});
	view->addSubview(subview);
	subview=CAView::createWithLayout(DLayout(DHorizontalLayout_L_W(width+40, width), DVerticalLayout_T_H(550, 100)), themeColor);
	img=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(5, 45), DVerticalLayout_H_C(45, 0.5)));
	img->setImage(CAImage::create("img/help.png"));
	subview->addSubview(img);
	label=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(55, 150), DVerticalLayout_H_C(45, 0.5)));
	label->setText("帮扶专区");
	label->setFontSize(35);
	label->setColor(CAColor4B::WHITE);
	subview->addSubview(label);
	view->addSubview(subview);
	subview=CAView::createWithLayout(DLayout(DHorizontalLayout_L_W(width*2+60, width), DVerticalLayout_T_H(550, 100)), themeColor);
	img=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(5, 45), DVerticalLayout_H_C(45, 0.5)));
	img->setImage(CAImage::create("img/mall.png"));
	subview->addSubview(img);
	label=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(55, 150), DVerticalLayout_H_C(45, 0.5)));
	label->setText("农资商城");
	label->setFontSize(35);
	label->setColor(CAColor4B::WHITE);
	subview->addSubview(label);
	view->addSubview(subview);
	//政策资讯
	sendHttp(view, "/api/appInfor/getAppList", "page=0&size=30&sort=inforId,desc", CALLBACK_BIND_1(HomeController::infoData, this), CAHttpRequest::Type::Get, true, false);
	//推荐品类
	sendHttp(view, "/api/appHelpPoorGoods/queryType", "", CALLBACK_BIND_1(HomeController::typeData, this), CAHttpRequest::Type::Get, true, false);
	//推荐商品
	commoditys=CAAutoCollectionView::createWithLayout(DLayout(DHorizontalLayout_L_R(10, 10), DVerticalLayout_T_B(860, 20)));
	commoditys->setAllowsSelection(true);
	commoditys->setOrientation(CAAutoCollectionView::Orientation::Vertical);
	commoditys->setHeaderRefreshView(CAPullToRefreshView::create(CAPullToRefreshView::Type::Header));
	commoditys->setFooterRefreshView(CAPullToRefreshView::create(CAPullToRefreshView::Type::Footer));
	commoditys->setHoriCellInterval(20);
	commoditys->setVertCellInterval(20);
	commoditys->onCellAtIndexPath(CALLBACK_BIND_3(HomeController::collectionCellAtIndex, this));
	commoditys->onCellSizeAtIndexPath(CALLBACK_BIND_2(HomeController::collectionViewCellSizeAtIndexPath, this));
	commoditys->onNumberOfItemsAtIndexPath(CALLBACK_BIND_1(HomeController::numberOfItemsInSection, this));
	commoditys->onDidSelectCellAtIndexPath(CALLBACK_BIND_2(HomeController::collectionViewDidSelectCellAtIndexPath, this));
	commoditys->onHeaderBeginRefreshing(CALLBACK_BIND_0(HomeController::scrollViewHeaderBeginRefreshing, this));
	commoditys->onFooterBeginRefreshing(CALLBACK_BIND_0(HomeController::scrollViewFooterBeginRefreshing, this));
	view->addSubview(commoditys);
	sendHttp(view, "/api/appHelpPoorGoods/homeRecommend", "page=0&size=30", CALLBACK_BIND_1(HomeController::commodityData, this));
}

void HomeController::bananerData(const string& data){
	CSJson::Value value;
	CSJson::Reader reader;
	bool flag=reader.parse(data, value);
	CC_RETURN_IF(!flag);
	size=value.size();
	for(int i=0; i<size; i++){
		const char* url=value[i]["picture"].asCString();
		CAHttpRequest* http=CAHttpRequest::create();
		http->setUrl(url);
		http->setRequestType(CAHttpRequest::Type::Get);
		http->setResponseCallback([=](CAHttpClient* client, CAHttpResponse* res){
			if(res->isSucceed()){
				const char* key=value[i]["pictureName"].asCString();
				CAImageView* img=CAImageView::createWithImage(CAImage::createWithImageData(res->getResponseData(), key));
				imgs.pushBack(img);
			}
			if(i==size-1){
				bananers();
			}
		});
		CAHttpClient::getInstance(2)->send(http);
	}
}

void HomeController::bananers(){
	CAView* view=this->getView();
	CAView* subview=CAView::createWithLayout(DLayout(DHorizontalLayout_L_R(20, 20), DVerticalLayout_T_H(130, 400)));
	pageView=CAPageView::createWithLayout(DLayoutFill, CAPageView::Orientation::Horizontal);
	pageView->onEndTurning([&]{
		pageControl->setCurrentPage(pageView->getCurrPage());
		pageControl->updateCurrentPageDisplay();
	});
	pageView->setViews(imgs);
	subview->addSubview(pageView);
	pageControl=CAPageControl::createWithLayout(DLayout(DHorizontalLayout_W_C(100, 0.5), DVerticalLayout_B_H(20, 50)));
	pageControl->setNumberOfPages(size);
	pageControl->setPageIndicatorTintColor(CAColor4B::GRAY);
	pageControl->setCurrentPageIndicatorTintColor(CAColor4B::GREEN);
	pageControl->setTarget([&](int index){
		pageView->setCurrPage(index, true);
	});
	subview->addSubview(pageControl);
	view->addSubview(subview);
	//自动播放轮播图
	CAScheduler::getScheduler()->schedule([&](float interval){
		int currPage=pageView->getCurrPage()+1;
		currPage=(currPage==size)?0:currPage;
		pageView->setCurrPage(currPage, true);
		pageControl->setCurrentPage(currPage);
		pageControl->updateCurrentPageDisplay();
	}, "auto_rotation", this, 10);
}

void HomeController::infoData(const string& data){
	CSJson::Value value;
	CSJson::Reader reader;
	bool flag=reader.parse(data, value);
	CC_RETURN_IF(!flag);
	CSJson::Value val=value["content"];
	int total=val.size();
	
	CAView* view=this->getView();
	CAView* subview=CAView::createWithLayout(DLayout(DHorizontalLayout_L_R(20, 20), DVerticalLayout_T_H(670, 100)));
	CAImageView* img=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(20, 58), DVerticalLayout_H_C(74, 0.5)));
	img->setImage(CAImage::create("img/info.png"));
	subview->addSubview(img);
	CADrawView* drawView=CADrawView::create();
	drawView->setLayout(DLayout(DHorizontalLayout_L_W(50, 5), DVerticalLayout_T_H(100, 74)));
	drawView->drawLine(DPoint(50, 85), DPoint(50, 160), ccc4(204, 204, 204, 255));
	subview->addSubview(drawView);
	CALabel* info=nullptr;
	CAVector<CAView*> infos;
	for(int i=0; i<total; i++){
		info=CALabel::createWithLayout(DLayoutFill);
		info->setText(val[i]["inforName"].asCString());
		info->setFontSize(35);
		info->setColor(CAColor4B::BLUE);
		info->setTextAlignment(CATextAlignment::Left);
		info->setVerticalTextAlignmet(CAVerticalTextAlignment::Center);
		info->onTouchBegan([](CATouch* touch, CAEvent* event){
		    getRootWindow()->pushViewController(PlayerController::create(), true);

		    return true;
		});
		infos.pushBack(info);
	}
	pageInfo=CAPageView::createWithLayout(DLayout(DHorizontalLayout_L_R(120, 0), DVerticalLayout_H_C(100, 0.5)), CAPageView::Orientation::Vertical);
	pageInfo->setViews(infos);
	subview->addSubview(pageInfo);
	view->addSubview(subview);
	//自动滚动消息
	CAScheduler::getScheduler()->schedule([=](float interval){
		int currPage=pageInfo->getCurrPage()+1;
		currPage=(currPage==total)?0:currPage;
		pageInfo->setCurrPage(currPage, true);
	}, "auto_info", pageInfo, 1);
}

void HomeController::typeData(const string& data){
	CSJson::Value value;
	CSJson::Reader reader;
	bool flag=reader.parse(data, value);
	CC_RETURN_IF(!flag);

	CAListView* types=CAListView::createWithLayout(DLayout(DHorizontalLayout_L_R(10, 10), DVerticalLayout_T_H(790, 60)));
	types->setOrientation(CAListView::Orientation::Horizontal);
	types->setReachBoundaryHandOverToSuperview(false);
	types->setSeparatorColor(CAColor4B::WHITE);
	types->setShowsScrollIndicators(false);
	types->setAllowsSelection(true);
	types->setSelectAtIndex(0);
	types->onNumberOfRowsAtIndexPath([=](){
		return value.size()+1;
	});
	types->onCellHeightAtIndexPath([](unsigned int index){
		return 120;
	});
	types->onCellAtIndexPath([=](const DSize& cellSize, unsigned int index){
		CAListViewCell* cell=(CAListViewCell*)types->dequeueReusableCellWithIdentifier("type_cell");
		if(!cell){
			cell=CAListViewCell::create("type_cell");
			CALabel* label=CALabel::createWithLayout(DLayoutFill);
			label->setVerticalTextAlignmet(CAVerticalTextAlignment::Center);
			label->setTextAlignment(CATextAlignment::Center);
			label->setColor(CAColor4B::BLACK);
			label->setFontSize(40);
			label->setTag(100);
			cell->addSubview(label);
		}

		CALabel* label=(CALabel*)cell->getSubviewByTag(100);
		if(index==0){
			if(selectType==0){
				label->setColor(themeColor);
				label->setFontSize(50);
			}
			label->setText("推荐");
		}else{
			label->setText(value[index-1]["speciesName"].asCString());
		}
		
		return cell;
	});
	types->onDidSelectCellAtIndexPath([=](unsigned int index){
		CAListViewCell* cell=types->cellForRowAtIndex(selectType);
		CALabel* label=(CALabel*)cell->getSubviewByTag(100);
		label->setColor(CAColor4B::BLACK);
		label->setFontSize(40);
		cell=types->cellForRowAtIndex(index);
		cell->setControlState(CAControl::State::Normal);
		label=(CALabel*)cell->getSubviewByTag(100);
		label->setColor(themeColor);
		label->setFontSize(50);
		selectType=index;

		if(index==0){
			typeCode=0;
		}else{
			typeCode=value[index-1]["speciesId"].asUInt();
		}
		commoditys->startPullToHeaderRefreshView();
	});
	types->onWillDisplayCellAtIndexPath([=](CAListViewCell* cell, unsigned int index){
		if(index==0){
			cell->setControlState(CAControl::State::Normal);
		}
	});

	this->getView()->addSubview(types);
}

void HomeController::scrollViewHeaderBeginRefreshing(){
	page=0;
	string para="page=0&size=10";
	if(typeCode>0){
		para.append(obj2str("&typeCode=%d", typeCode));
	}
	sendHttp(this->getView(), "/api/appHelpPoorGoods/homeRecommend", para, CALLBACK_BIND_1(HomeController::commodityData, this));
}

void HomeController::scrollViewFooterBeginRefreshing(){
	string para=obj2str("page=%d&size=10", ++page);
	if(typeCode>0){
		para.append(obj2str("&typeCode=%d", typeCode));
	}
	sendHttp(this->getView(), "/api/appHelpPoorGoods/homeRecommend", para, CALLBACK_BIND_1(HomeController::commodityData, this));
}

void HomeController::collectionViewDidSelectCellAtIndexPath(unsigned int section, unsigned int item){
	CACollectionViewCell* cell=commoditys->cellForRowAtIndexPath(section, item);
	cell->getContentView()->setRotation(-360);
	cell->getContentView()->setScale(0.5f);
	CAViewAnimation::beginAnimations("");
	cell->getContentView()->setRotation(0);
	cell->getContentView()->setScale(1.0f);
	CAViewAnimation::commitAnimations();
}

void HomeController::collectionViewDidDeselectCellAtIndexPath(unsigned int section, unsigned int item){
}

CACollectionViewCell* HomeController::collectionCellAtIndex(const DSize& cellSize, unsigned int section, unsigned int item){
	CACollectionViewCell* cell=commoditys->dequeueReusableCellWithIdentifier("commodity_cell");

	if(cell==nullptr){
		cell=CACollectionViewCell::create("commodity_cell");

		CAImageView* itemImage=CAImageView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_H(0, 320)));
		itemImage->setTag(1);
		cell->getContentView()->addSubview(itemImage);
		CALabel* itemText=CALabel::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_H(330, 30)));
		itemText->setTag(2);
		itemText->setFontSize(40);
		itemText->setTextAlignment(CATextAlignment::Left);
		itemText->setVerticalTextAlignmet(CAVerticalTextAlignment::Center);
		cell->getContentView()->addSubview(itemText);
	}

	CSJson::Value val=commodityDatas[item];
	CAImageView* itemImageView=(CAImageView*)cell->getContentView()->getSubviewByTag(1);
	CALabel* itemText=(CALabel*)cell->getContentView()->getSubviewByTag(2);
	itemText->setText(val["title"].asCString());

	const string& url=val["images"].asCString();
	CAHttpRequest* http=CAHttpRequest::create();
	http->setUrl(url);
	http->setRequestType(CAHttpRequest::Type::Get);
	http->setResponseCallback([=](CAHttpClient* client, CAHttpResponse* res){
		if(res->isSucceed()){
			const string& key=val["helpPoorGoodsId"].asCString();
			itemImageView->setImage(CAImage::createWithImageData(res->getResponseData(), key));
		}
	});
	CAHttpClient::getInstance(2)->send(http);

	return cell;
}

DSize HomeController::collectionViewCellSizeAtIndexPath(unsigned int section, unsigned int item){
	return DSize(340, 460);
}

unsigned int HomeController::numberOfItemsInSection(unsigned int section){
	return commodityDatas.size();
}

void HomeController::commodityData(const string& data){
	CSJson::Value value;
	CSJson::Reader reader;
	bool flag=reader.parse(data, value);
	CC_RETURN_IF(!flag);

	CSJson::Value val=value["content"];
	int length=val.size();
	if(page==0){
		commodityDatas=val;
	}else{
		for(int i=0; i<length; i++){
			commodityDatas.append(val[i]);
		}
	}
	commoditys->reloadData();
}